from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship

# 创建模型的基类
Base = declarative_base()


# 定义Address模型，映射到addresses表
class Address(Base):
    __tablename__ = 'addresses'

    id = Column(Integer, primary_key=True)
    email_address = Column(String(length=255), nullable=False)  # 为VARCHAR类型添加长度
    user_id = Column(Integer, ForeignKey('users.id'))

    # 使用back_populates参数来避免双向关系中的冗余
    user = relationship("User", back_populates="addresses")

    def __repr__(self):
        return f"<Address(email_address='{self.email_address}')>"


# 定义User模型，映射到users表
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String(length=255))  # 为VARCHAR类型添加长度
    fullname = Column(String(length=255))  # 为VARCHAR类型添加长度
    nickname = Column(String(length=255))  # 为VARCHAR类型添加长度

    # 假设User有一个与之关联的地址列表
    addresses = relationship("Address", order_by=Address.id, back_populates="user")

    def __repr__(self):
        return f"<User(username='{self.username}', fullname='{self.fullname}', nickname='{self.nickname}')>"


# 创建数据库引擎
engine = create_engine('mysql://root:123456@124.70.50.228:3306/weixin')

# 创建所有定义的表
Base.metadata.create_all(engine)
